import { Component, OnInit } from '@angular/core';
import { CommonResponse,ToastColor,CommonService } from '@services/common-service.service';
import { AuthTokenService } from '@services/auth-token.service';
import {HttpClient} from "@angular/common/http";
import { EventEmitterService,EventName } from '@services/event-emitter.service';
import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
import { ActionSheetController,AlertController } from '@ionic/angular';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { TranslateService } from '@ngx-translate/core';
import { DefaultLanguageService } from '@services/default-language.service';

@Component({
  selector: 'app-user-name',
  templateUrl: './user-name.page.html',
  styleUrls: ['./user-name.page.scss'],
})
export class UserNamePage implements OnInit {

  public defaultPhotoUrl:string = 'assets/images/ios/proof of identity@3x.png';

  public loading:boolean = false;

  public appUser:any = {
    userName:'',
    photoUrl:'assets/images/ios/proof of identity@3x.png'
  }

  public i18n:any = {};
  constructor(
    private commonService:CommonService,
    private authTokenService:AuthTokenService,
    private http:HttpClient,
    private eventEmitterService:EventEmitterService,
    private camera: Camera,
    private actionSheetController:ActionSheetController,
    private translate: TranslateService,
    private defaultLanguageService:DefaultLanguageService) { 
      this.initLanguage();
    }

  initLanguage(){
    this.i18n = this.commonService.initTranslate(['myAccount.setting.personal_informations.user_name']); 
  }
  
  public validateForm:FormGroup;  
  ngOnInit() {
    this.validateForm = new FormGroup({
      'userName': new FormControl('', [
        Validators.required
      ])
    });
    this.getAppUser();
  }

  get userName() { return this.validateForm.get('userName'); }
  
  getAppUser(){
    let appUserId = this.authTokenService.getAppUserId();
    this.commonService.getAppUser(appUserId).subscribe((response:CommonResponse)=>{
      if(response.isSuccess){
        this.appUser = response.responseBody;
        if(!this.appUser.photoUrl){
          this.appUser.photoUrl = this.defaultPhotoUrl;
        }
      }
    },(errorResponse)=>{
      this.commonService.commonToast(ToastColor.warning,errorResponse.error.errorMsg);
    });
  }

  async openSelectPicture(){
    const actionSheet = await this.actionSheetController.create({
      header: '',
      keyboardClose:true,
      buttons: [
      {
        text: this.i18n.carema,
        role: '',
        icon: '',
        handler: () => {
          this.getPictureFromCamera(this.camera.PictureSourceType.CAMERA);
        }
      },
      {
        text: this.i18n.album,
        role: '',
        icon: '',
        handler: () => {
          this.getPictureFromCamera(this.camera.PictureSourceType.SAVEDPHOTOALBUM);
        }
      }, 
      {
        text: this.i18n.cancel,
        icon: '',
        role: 'cancel',
        handler: () => {
          //console.log('Cancel clicked');
        }
      }
      ]
    });
    await actionSheet.present();
  }

  /**
   * @param sourceType 
  * Defined in Camera.PictureSourceType. Default is CAMERA.
  *      PHOTOLIBRARY : 0,
  *      CAMERA : 1,
  *      SAVEDPHOTOALBUM : 2
  */
  getPictureFromCamera(sourceType:number){
    const options = {
      quality:100,
      destinationType:this.camera.DestinationType.DATA_URL,//DATA_URL:base64  FILE_URI:file uri
      sourceType:sourceType,
      encodingType:this.camera.EncodingType.JPEG,
      mediaType:this.camera.MediaType.PICTURE
    }
    this.camera.getPicture(options).then((imageData)=>{
      this.appUser.photoUrl = 'data:image/jpeg;base64,' +imageData;
    })
  }

  updateUserNameAndPhoto(){
    if(this.validateForm.invalid){
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
      return false;
    }
    this.loading = true;
    var api = "/scm/app/updateUserNameAndPhoto.do";
    let requestJson = {
      appUserId:this.authTokenService.getAppUserId(),
      userName:this.validateForm.value.userName,
      photoUrl:this.appUser.photoUrl
    }
    this.http.post(api,requestJson).subscribe((response:CommonResponse)=>{
      if(response.isSuccess){
        this.eventEmitterService.eventEmit.emit(EventName.USERNAME_PHOTO_CHANGED);
        this.commonService.commonToast(ToastColor.success,this.i18n.save_success);
      }else{
        this.commonService.commonToast(ToastColor.warning);
      }
      this.loading = false;
    },(errorResponse)=>{
      this.commonService.commonToast(ToastColor.warning,errorResponse.error.errorMsg);
      this.loading = false;
    });
  }
}
